package absolute_zero.com.urbox;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.SavedState;
/**
 * Main Activity for UrBox P2P application
 * 
 * @author Maliek Mckight
 * @version 0.10
 *
 */
public class urbox extends Activity {
	//Instance Variables
		ListView menu;
    //Screen alert
    private Builder alert;
    private Builder confirm;
    //Pass to next activity
    Bundle screen_info;
    Intent next_intent;
    File currentDirectory;
    Context context;

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instantiate();
	}
	
	public void instantiate() {
		setContentView(R.layout.main);
		context = urbox.this;
		//create UrBox Directory
		  File subdirectory = null;
	        File basedirectory = new File("/sdcard");
	        subdirectory = new File( basedirectory, "/urbox/tmp");
			if ( ! subdirectory.exists() ) {
			    Log.i( "Update", "attempt to create subdirectory: " +	subdirectory );
			    subdirectory.mkdirs();          // makes all subdir levels you need
			} 

	
			//set up ListView
			ListView menu = (ListView)findViewById(R.id.Action_list);
			
			//set up adapter to list vieW
			Icon_text_list_adapter itla = new Icon_text_list_adapter(this);

	        // Add Items to list view.
	        itla.addItem(new Icon_text(
	               "Send File", getResources().getDrawable(R.drawable.send_file)));
	        itla.addItem(new Icon_text(
	               "Browse UrBox", getResources().getDrawable(R.drawable.browse)));
	        itla.addItem(new Icon_text(
	               "File Log", getResources().getDrawable(R.drawable.writing_star)));
	        itla.addItem(new Icon_text(
	               "Invite", getResources().getDrawable(R.drawable.invite)));
	        
	        // Display it
	        menu.setAdapter(itla); 
	        Log.d("status","waiting for input");
	        menu.setOnItemClickListener(new OnItemClickListener(){

				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO: launch activity based on selection	
					switch(arg2){
						case 0: /* Send File */
							 next_intent = new Intent(urbox.this, urbox_send.class);
							  screen_info = new Bundle();
							  	startActivityForResult(next_intent, 0x1337);
							  	instantiate();
							break;
						case 1: /* Browse UrBox */
							setContentView(R.layout.send_file);
							browseFiles(new File("/sdcard/urbox"));
							Button back = (Button)findViewById(R.id.Back_to_send_filetype);
							back.setOnClickListener(new OnClickListener(){

								public void onClick(View v) {
									instantiate();
									
								}
							
							});
							break;
						case 2: /* Log file */
							setContentView(R.layout.log);
							Button ok_button = (Button)urbox.this.findViewById(R.id.ok_button_1);
							//To get the list of things to fill to ListAdapter parse out the log.txt files
							//set up ListView
							ListView log_menu = (ListView)findViewById(R.id.Action_list);
							//set up adapter to list vieW
							Icon_text_list_adapter log_itla = new Icon_text_list_adapter(context);
							//get file
							File f = new File(Environment.getExternalStorageDirectory().getPath() + "/urbox/log.txt");
							if(f.exists()){
								FileInputStream fileIS = null;
								try {
									fileIS = new FileInputStream(f);
								} catch (FileNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
								String read = new String();
								try {
									while((read = buf.readLine()) != null && read.contains("\t")){
									    //Do Something Which each line of data read
									    log_itla.addItem(parse(read));
										
									}
									log_menu.setAdapter(log_itla);
									buf.close();
									fileIS.close();
									
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} 
							}else{
								//Put a blank ?
								log_itla.addItem(new Icon_text("You have not sent any files yet!", getResources().getDrawable(R.drawable.symbol_question)));
								//Display
								log_menu.setAdapter(log_itla);
							}
							ok_button.setVisibility(0);
							ok_button.setOnClickListener(new OnClickListener(){

								@Override
								public void onClick(View v) {
									urbox.this.instantiate();
									
								}
								});
							break;
						case 3: /* Invite Others */
							Uri uri = Uri.parse("sms:");
							Intent i = new Intent(Intent.ACTION_VIEW, uri);
	                    	i.putExtra("sms_body", "Test Message!!!");
	                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	                    	startActivity(i);
	                        instantiate();
							break;
					}					
				}

				private Icon_text parse(String read) {
					// create adapter item from list
					String[] items = read.split("\t");
					Log.d("Array says", items[0] + " , " + items [1] + " , " + items[2]);
					/*
					 * 0 - File Name
					 * 1 - Recipient
					 * 2 - Status
					 */
					Drawable drawable;
					if(items[2].equals("Sucess") || items[2].trim().equalsIgnoreCase("accepted")){
						drawable = getResources().getDrawable(R.drawable.symbol_ok);
					}else{
						if(items[2].equals("Failure")){
							drawable = getResources().getDrawable(R.drawable.x_mark);
						}else{
								drawable = getResources().getDrawable(R.drawable.symbol_question);
						}
					}
					return new Icon_text("Sent " + items[0] + " to " + items[1] + ".  Result: " + items[2], drawable);
					
				}

				
	        });
		}
		
	
	public void browseFiles(final File aDirectory){
    	//Check location  	
    	Log.d("Current Location:", aDirectory.toString());
    	Log.d("Is a Directory:", aDirectory.isDirectory() + "");
    	
        //Code to determine if folder or file and how to handle
        if (aDirectory.isDirectory()){
            this.currentDirectory = aDirectory;
            openFile(aDirectory);
        }
        else{
            alert = new AlertDialog.Builder(urbox.this)
            	/**TODO: Finish setting options for buttons or make new menu*/
	            .setTitle("File Options")
	            .setMessage("What do you want to do with this file?")
	            .setPositiveButton("Send", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	Intent i = new Intent(urbox.this, ContactSearch.class);
	                    	Bundle UserInfo = new Bundle();
	                        //Log.d("here's the file", aDirectory.getAbsolutePath());
	                    	UserInfo.putString("Filepath", aDirectory.getAbsolutePath());
	                        i.putExtras(UserInfo);
	                        startActivityForResult(i, 0x1337);
	                    }
	            })
	            .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                            //Do Nothing
	                    }
	            })
	            .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                            confirmDialog(aDirectory, "delete");
	                    }
            });
            alert.show();
       } 
    }
	 @Override
	    protected void onActivityResult( int requestCode, int resultCode,
	    Intent data ){
		 instantiate();
		 super.onActivityResult(requestCode, resultCode, data);
	 }
    //Returns back to the root file (presumably the sdcard)
    public void browseToRoot(){
    	browseFiles(new File("/sdcard/urbox"));
    }
    
    //Goes up one folder in the directory
    public void upOneLevel(){
    	Log.d("where a i?", this.currentDirectory.getPath().toString());
    	if(this.currentDirectory.getParent() != null && this.currentDirectory.getPath().toString().contains("/sdcard/urbox/")){
    		 browseFiles(this.currentDirectory.getParentFile());
    	}
    } 
    
    //Opens the folder clicked on
    public void openFile(File aFile){
        fill((aFile.getAbsoluteFile()).listFiles());
    } 
    
    // Checks whether checkItsEnd ends with one of the Strings from fileEndings 
    private boolean checkEndsWithInStringArray(String checkItsEnd,
                        String[] fileEndings){
         for(String aEnd : fileEndings){
              if((checkItsEnd.toLowerCase()).endsWith(aEnd))
                   return true;
         }
         return false;
    }
    
    //Displays and adds listeners to the files in a directory
    public void fill(final File files[]){
    	//Setup Browser
    	ListView fileBrowser = (ListView)findViewById(R.id.File_list);
    	//Set up adapter to Browser
		Icon_text_list_adapter itla = new Icon_text_list_adapter(this);
		
        // Add Items to Browser
        itla.addItem(new Icon_text(
               "Back to Root", getResources().getDrawable(R.drawable.back_arrow)));
        itla.addItem(new Icon_text(
               "Up-Folder", getResources().getDrawable(R.drawable.up_arrow)));
        
        for(int i = 0; i < files.length; i++){
        	if(files[i].isDirectory()){
        		itla.addItem(new Icon_text(
                		files[i].getName(), getResources().getDrawable(R.drawable.folder)));
        	}
        	else
        	
	            /* Determine the Icon to be used,
	             * depending on the FileEndings defined in:
	             * res/values/fileendings.xml. */
	            if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingImage))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.image)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingWebText))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.webtext)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingPackage))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.archive)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingAudio))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.audio)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	            					getStringArray(R.array.fileEndingText))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.text)));
	            }    
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
    								getStringArray(R.array.fileEndingVideo))){
	            	itla.addItem(new Icon_text(
	            			files[i].getName(), getResources().getDrawable(R.drawable.video)));
	            }
	            else{
	        		itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.blank_file)));
	            }
	        }
        
        // Display it
        fileBrowser.setAdapter(itla);
        
        // Set the click listener
        fileBrowser.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// Make the files/directories clickable
				if(arg2 == 0){
					browseToRoot();
				}			
				else if(arg2 == 1){
					upOneLevel();
				}
				else {
					browseFiles(files[arg2 - 2]);
				}
			}
        });
    }

    public void confirmDialog(final File destroyDirectory, String action){
    	confirm = new AlertDialog.Builder(urbox.this)
    	.setMessage("Are you sure you wish to " + action + "?")
    	.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                		destroyDirectory.delete();
                		browseFiles(currentDirectory);
                }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                        //Do Nothing
                }
        });
    	confirm.show();
    }    
	    
	    public boolean checkInternet() {
		// Check to see if we're connected to the Internet
		ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
				|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
			return true;
		} else { 
			// We're not online. Oh noes! Handle this
			alert = new AlertDialog.Builder(urbox.this)
			.setTitle("No Connection")
			.setMessage("You are not currently connected to the Internet.  Setup an Internet connection and try again.")
			.setNeutralButton("Retry", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					//Restart the activity
					checkInternet();
				}
			});
			alert.show();
			return false;
		}
	}

/** Called when screen is flipped **/
@Override
public void onConfigurationChanged(Configuration newConfig) {
	super.onConfigurationChanged(newConfig);
}

/** Reads an Input Stream and converts into string.  Used for processing server responses. **/
public static String stream_reader (InputStream in) throws IOException {
	StringBuffer out = new StringBuffer();
	byte[] b = new byte[4096];
	for (int n; (n = in.read(b)) != -1;) {
		out.append(new String(b, 0, n));
	}
	return out.toString();
}

}